/*
 * Copyright (C) 2023 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     <url id="cvrnrvoh9478co2lj2sg" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url> 
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>
 
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_pwm.h"
#include "iot_errno.h"
#include "hi_io.h"
 
#define MAX_DUTY_CYCLE 100
#define PWM_FREQUENCY 64000
#define BREATHING_STEP_DELAY 17500       // 调整后的步进延时
#define TASK_STACK_SIZE 4096
#define RED_PWM_CHANNEL 2
#define GREEN_PWM_CHANNEL 1
#define BLUE_PWM_CHANNEL 0
#define TOTAL_BREATHING_CYCLES 3
 
/* 配置LED的PWM通道 */
static void ConfigurePWMChannel(int targetGpioPin, int targetPwmChannel)
{
    IoTGpioInit(targetGpioPin);
    IoTGpioSetDir(targetGpioPin, IOT_GPIO_DIR_OUT);
    hi_io_set_func(targetGpioPin, 5);
    IoTPwmInit(targetPwmChannel);
}
 
static void SmoothBreathingEffect(int pwmChannel, int gpioPin)
{
    ConfigurePWMChannel(gpioPin, pwmChannel);
     
    // 渐亮阶段
    for (int dutyCycle = 1; dutyCycle <= MAX_DUTY_CYCLE; dutyCycle++) {
        IoTPwmStart(pwmChannel, dutyCycle, PWM_FREQUENCY);
        usleep(BREATHING_STEP_DELAY);
    }
     
    // 渐暗阶段
    for (int dutyCycle = MAX_DUTY_CYCLE; dutyCycle >= 1; dutyCycle--) {
        IoTPwmStart(pwmChannel, dutyCycle, PWM_FREQUENCY);
        usleep(BREATHING_STEP_DELAY);
    }
     
    IoTPwmStop(pwmChannel);
}
 
static void BreathingLightTask(void)
{
    static int remainingBreathingCycles = TOTAL_BREATHING_CYCLES;
 
    while (remainingBreathingCycles--) {
        SmoothBreathingEffect(RED_PWM_CHANNEL, 2);
        SmoothBreathingEffect(GREEN_PWM_CHANNEL, 8);
        printf("Smooth breathing effect running...\n");
        SmoothBreathingEffect(BLUE_PWM_CHANNEL, 7);
    }
}
 
static void StartBreathingTask(void)
{
    osThreadAttr_t taskConfiguration = {
        .name = "BreathingTask",
        .stack_size = TASK_STACK_SIZE,
        .priority = osPriorityNormal
    };
 
    if (osThreadNew(BreathingLightTask, NULL, &taskConfiguration) == NULL) {
        printf("[BreathingLight] Task creation failed!\n");
    }
}
 
APP_FEATURE_INIT(StartBreathingTask);